package com.feng.rabbitmq.three;

import com.feng.rabbitmq.utiils.RabbitMQUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import static java.lang.Thread.sleep;

/**
 * error:
 * Exception in thread "main" java.io.IOException
 * Caused by: com.rabbitmq.client.ShutdownSignalException:channel error; protocol method: #method<channel.close>
 *      (reply-code=404, reply-text=NOT_FOUND - no queue 'ask_queue' in vhost '/', class-id=60, method-id=20)
 *  错误原因：生产者没有开启，或者生产者的队列名和此消费者的队列名QUEUE_NAME不同导致的
 */
public class Work03 {
    public static final String QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();
        System.out.println("c3等待接收消息...");
        DeliverCallback deliverCallback = (consumerTag,message) ->{
          //沉睡
            try {
                sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接收到的消息："+new String(message.getBody()));
            //手动应答
            /**
             * 1. 消息的标记 tag
             * 2. 是否批量应答 false：不，true：批量
             */
//            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };
        CancelCallback cancelCallback = consumerTag ->{
            System.out.println(consumerTag+"消费者取消消费接口回调逻辑");
        };
        //设置不公平分发
        //默认0，为公平分发
        //预取值
        int prefetchCount = 2;
        channel.basicQos(prefetchCount);
        //采取手动应答
        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME,autoAck,deliverCallback,(consumerTag->{
            System.out.println(consumerTag+"消费者取消消费接口回调逻辑");
        }));
    }
}
